#include <stdio.h>
#include <stdlib.h>

typedef double (*Operation)(double, double);    

double add(double a, double b) {
    return a + b;
}

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    if (b == 0) {
        fprintf(stderr, "错误：除数不能为零！\n");
        exit(EXIT_FAILURE);
    }
    return a / b;
}

double calculate(double a, double b, char op, Operation operations[]) {
    switch (op) {
        case '+': return operations[0](a, b);
        case '-': return operations[1](a, b);
        case '*': return operations[2](a, b);
        case '/': return operations[3](a, b);
        default:
            fprintf(stderr, "错误：无效运算符 '%c'\n", op);
            exit(EXIT_FAILURE);
    }
}

int main() {
    // 初始化函数指针数组
    Operation operations[4] = {add, subtract, multiply, divide};
    
    double a, b;
    char op;
    
    printf("简单计算器 (支持 + - * /)\n");
    printf("输入格式: 数字1 运算符 数字2 (例: 2.5 * 4)\n");
    printf("输入 q 退出\n\n");
    
    while (1) {
        printf("> ");
        if (scanf("%lf %c %lf", &a, &op, &b) != 3) {
            // 检查退出指令
            char ch;
            scanf("%c", &ch);
            if (ch == 'q') break;
            
            printf("错误：无效输入格式！\n");
            // 清除输入缓冲区
            while (getchar() != '\n');
            continue;
        }
        
        // 进行计算并输出结果
        double result = calculate(a, b, op, operations);
        printf("结果: %.2lf\n\n", result);
    }
    
    printf("计算器已退出\n");
    return 0;
}